#include "IO/model.hpp"
#include <iomanip>
#include <sstream>

Model::Model()
{
	m_count = 0;
	GetImageFlag = false;
	//m_time = getTickCount();
	fout.open("Output/result.txt");
}

void Model::Get(const I_Rect &_selection)
{
	box.x = _selection.x;box.y = _selection.y;box.width = _selection.width;box.height = _selection.height;
}

void Model::Get(const std::vector<I_Rect> &_selections)
{
	for(size_t i=0;i<boxes.size();i++)
	{
		boxes[i].x = _selections[i].x;
		boxes[i].y = _selections[i].y;
		boxes[i].width = _selections[i].width;
		boxes[i].height = _selections[i].height;
		boxes[i].color[0] = _selections[i].color[0];
		boxes[i].color[1] = _selections[i].color[1];
		boxes[i].color[2] = _selections[i].color[2];
	}
	size_t j = boxes.size();
	//std::cout << _selections.size() << j << std::endl;
	while(boxes.size()<_selections.size())
		boxes.push_back(_selections[j++]);
}

void Model::Get(const I_Point &_point)
{
	point.x = _point.x; point.y = _point.y;
}

void Model::Get(const Image &_image)
{
	if(_image.channel==0)
		_image.Convert(rst_img);
	else
		_image.CopyTo(rst_img);
	GetImageFlag = true;
}

string Model::GetInfo()
{
	std::stringstream str;
    str << "Frame : "  << std::setiosflags(std::ios::left) << std::setw(5) << m_count
	   << "Total FPS: " << std::setiosflags(std::ios::left) << std::setprecision(4) << std::setw(7) /* << m_fps */;
    return str.str();
}

Image& Model::Result()
{
	if(!GetImageFlag)
		src_img.CopyTo(rst_img);
	for(size_t i=0;i<boxes.size();i++)
	{
		rst_img.Draw(boxes[i]);
		if(point.x!=0 || point.y !=0)
		{
			rst_img.Draw(point,I_Point(boxes[i].x,boxes[i].y));
			//fout << point.x << "," << point.y <<endl;
		}

	}
	return rst_img;
}
void Model::OutputBoxes()
{
    for(size_t i=0;i<t_boxes[m_count-1].size();i++)
    {
        fout << "##" << i << ":"<<endl;
        for(size_t j=0;j<t_boxes.size();j++)
        {
            if(i<t_boxes[j].size())
                fout << "  #" << j << ":" <<t_boxes[j][i].x << "," << t_boxes[j][i].y << endl;
                else
                fout <<"  #" << j << ":" << -1 << "," << -1 << endl;
        }
    }
    Log("Output Result!");
}

void Model::AddFrame()
{
	m_count++;
	GetImageFlag = false;
	//if(m_count >1)
    //    fout << "  #" << m_count-1 << ":" << boxes[0].x << "," << boxes[0].y  << ":" << point.x << "," << point.y << endl;
	t_boxes.push_back(boxes);
}

void Model::PreFrame()
{
	if(m_count>1)
		m_count--;
	GetImageFlag = false;
	t_boxes.erase(t_boxes.end());
	boxes = t_boxes[m_count-1];
}
